package org.crazyrunner.common.dao;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import org.crazyrunner.common.page.PagingSupport;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

@Repository("hibernateBaseDao")
public class  HibernateBaseDao<T>  extends HibernateDaoSupport{
	/**
	 * spring和hibernate兼容性问题，导致无法根据sessionFactory注入。采用自定义注入sessionFactory 
	 * @param hibernateSessionFactory
	 */
	@Resource(name="sessionFactory")
	public void setHibernateSessionFactory(SessionFactory hibernateSessionFactory) {
		super.setSessionFactory(hibernateSessionFactory);
	}

//	private Class<T> clazz;
	public HibernateBaseDao() {
//		Type type = this.getClass().getGenericSuperclass();
//		try {
//			clazz = (Class<T>) ((ParameterizedType)type).getActualTypeArguments()[0];
//		} catch (Exception e) {
//			//there caught an Exception,because not called by implementation
//			//DoNothing
//		}
	}
	
	public Session getCurrentSession() {
		return this.getSessionFactory().getCurrentSession();
	}
	public void flush(){
		this.getCurrentSession().flush();
	}
	public void clear(){ 
		this.getCurrentSession().clear();
	}
		
	public T get(Class<T> clazz,Serializable id){
		return getHibernateTemplate().get(clazz, id);
	}
	
	public Serializable save(T t){
		return getHibernateTemplate().save(t);
	}
	
	public void deleteById(Class<T>clazz ,Serializable id){
		getHibernateTemplate().delete(get(clazz, id));
	}
	
	public void deleteAll(Collection<T> entities){
		getHibernateTemplate().deleteAll(entities);
	}
	
	
	@SuppressWarnings("unchecked")
	public List<T> findAll(DetachedCriteria dc) {
		return dc.getExecutableCriteria(getCurrentSession()).list();
	}
	/**
	 * 通用分页查询
	 * @param pagingSupport 对象
	 * @param dc 离线查询对象
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public PagingSupport<T> findByPaging(PagingSupport<T> pagingSupport,DetachedCriteria dc){
		Criteria criteria = dc.getExecutableCriteria(getCurrentSession())
			.setProjection(Projections.rowCount());
		int count =  ((Long) criteria.uniqueResult()).intValue();
		pagingSupport.setRowCount(count);
		
		criteria.setProjection(null)
			.setFirstResult(pagingSupport.getFirstResult())
			.setMaxResults(pagingSupport.getPageSize());
		pagingSupport.setList(criteria.list());
		return pagingSupport;
	}
	
	
	
	
}
